import _ from 'lodash'
import ebus from 'libs/ebus.js'
import {getUrlPrefix, webAppApi} from '../../api.js'
import * as types from '../mutation-types'

function makeWebapps(webapps, language) {
  _.forEach(webapps, (item, index) => {
    item.link = getUrlPrefix() + '/' + item.pluginId + '?lang=' + language
    item.iconlink = item.link + '/static/img/' + item.icon
    item._id = index + 1
    item.state = 'link'
    if (item.i18n) {
      let i18n = JSON.parse(item.i18n)
      if (i18n && i18n[language]) {
        item.name = i18n[language].name
      }
    }
  })
}

export function doLoadWebapps({dispatch, state}, {init = false} = {}) {
  if (init && state.webapp.init) {
    return
  }
  dispatch(types.REFRESH_WEBAPPS_START)
  webAppApi.getStore().then(function(res) {
    if (res && res.data && res.data.code === 0) {
      var webapps = res.data.data.webapps
      let language = state.system.language
      makeWebapps(webapps, language)
      dispatch(types.SET_WEBAPPS, webapps)
    }
    dispatch(types.REFRESH_WEBAPPS_END)
  })
}

export function setWebAppState({dispatch}, id, val) {
  dispatch(types.SET_WEBAPP_STATE, id, val)
}